<template>
  <view class="my-evaluate-container">
    <!-- 1. 顶部导航栏 -->
    <view class="top-nav">
      <view class="nav-left" @click="navigateBack">
        <uni-icons class="back-icon" type="left" size="20" color="#fff"></uni-icons>
      </view>
      <text class="nav-title">我的评价</text>
      <view class="nav-right"></view> <!-- 占位保持居中 -->
    </view>

    <!-- 2. 评价列表区（滚动加载） -->
    <scroll-view 
      class="evaluate-list" 
      scroll-y 
      @scrolltolower="loadMoreEvaluates"
    >
      <!-- 加载中状态 -->
      <view class="loading-state" v-if="loading && evaluateList.length === 0">
        <uni-icons type="loading" size="30" color="#409EFF" spin></uni-icons>
        <text class="loading-text">加载评价中...</text>
      </view>

      <!-- 评价列表项 -->
      <view class="evaluate-item" v-for="(item, index) in evaluateList" :key="index">
        <!-- 工单基础信息（修复溢出） -->
        <view class="order-info">
          <view class="order-title" @click="toOrderDetail(item.orderId)">
            {{ item.orderTitle || '未命名工单' }}
          </view>
          <view class="order-meta">
            <text class="order-type">{{ item.orderTypeText || '未知类型' }}</text>
            <text class="order-time">工单提交：{{ formatDate(item.orderCreateTime) }}</text>
          </view>
        </view>

        <!-- 评价核心信息 -->
        <view class="evaluate-core">
          <!-- 评分（星星） -->
          <view class="star-rating">
            <text class="star" v-for="i in 5" :key="i" :class="{ active: i <= item.rating }">★</text>
          </view>
          <!-- 评价内容 -->
          <view class="evaluate-content">
            {{ item.comment || '无评价内容' }}
          </view>
          <!-- 评价时间 + 查看工单（强制居右） -->
          <view class="evaluate-meta">
            <text class="evaluate-time">评价时间：{{ formatDate(item.createTime) }}</text>
            <button class="view-order-btn" @click="toOrderDetail(item.orderId)">查看工单</button>
          </view>
        </view>
      </view>

      <!-- 空状态（无评价） -->
      <view class="empty-state" v-if="!loading && evaluateList.length === 0">
        <text class="empty-icon">📝</text>
        <text class="empty-text">您暂无评价记录，可在工单完成后提交评价</text>
        <button class="to-workorder-btn" @click="toWorkorderList">去查看我的工单</button>
      </view>

      <!-- 加载更多提示 -->
      <view class="load-more" v-if="!loading && evaluateList.length < totalCount">
        <text class="load-more-text">加载更多...</text>
      </view>
    </scroll-view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      token: uni.getStorageSync('token') || '', // 用户登录Token
      pageNo: 1,
      pageSize: 10,
      totalCount: 0, // 总评价数
      loading: false,
      evaluateList: [], // 评价列表（含工单关联信息）
    };
  },
  onLoad() {
    this.getMyEvaluateList(); // 页面加载时获取全部评价
  },
  methods: {
    navigateBack() {
      uni.navigateBack({ delta: 1 });
    },

    async getMyEvaluateList() {
      if (!this.token) {
        uni.showToast({ title: '请先登录', icon: 'none' });
        setTimeout(() => uni.redirectTo({ url: '/pages/login/login' }), 1500);
        return;
      }

      this.loading = true;
      try {
        const requestBody = {
          pageNo: this.pageNo,
          pageSize: this.pageSize
        };

        const response = await uni.request({
          url: 'http://localhost:6013/order-client/api/customerFeedback/queryPageList',
          method: 'POST',
          header: {
            'Content-Type': 'application/json',
            'Token': this.token
          },
          data: requestBody
        });

        const resData = response.data || {};
        if (resData.code !== 0) {
          throw new Error(resData.msg || '获取评价失败');
        }
        const pageData = resData.data || {};
        this.totalCount = pageData.total || 0;
        const newEvaluates = pageData.records || [];

        // 映射评价数据：从 workOrderInfo 中提取工单标题、类型、创建时间
        const mappedEvaluates = newEvaluates.map(item => ({
          id: item.id, 
          orderId: item.orderId, 
          // 优先从 workOrderInfo.title 取工单标题，无则显示“未命名工单”
          orderTitle: (item.workOrderInfo && item.workOrderInfo.title) || '未命名工单', 
          // 从 workOrderInfo.type 取工单类型，用于映射类型文本
          orderTypeText: this.mapOrderType(item.workOrderInfo && item.workOrderInfo.type), 
          // 从 workOrderInfo.createTime 取工单创建时间
          orderCreateTime: (item.workOrderInfo && item.workOrderInfo.createTime) || '', 
          rating: item.rating || 0, 
          comment: item.comment || '', 
          createTime: item.createTime || '' 
        }));

        // 合并分页数据
        if (this.pageNo === 1) {
          this.evaluateList = mappedEvaluates;
        } else {
          this.evaluateList = [...this.evaluateList, ...mappedEvaluates];
        }

      } catch (error) {
        let errMsg = '获取评价列表失败，请重试';
        if (error.message.includes('登录已过期')) {
          errMsg = '登录已过期，请重新登录';
          uni.removeStorageSync('token');
          setTimeout(() => uni.redirectTo({ url: '/pages/login/login' }), 1500);
        }
        uni.showToast({ title: errMsg, icon: 'none' });
      } finally {
        this.loading = false;
      }
    },

    loadMoreEvaluates() {
      if (this.loading || this.evaluateList.length >= this.totalCount) return;
      this.pageNo += 1;
      this.getMyEvaluateList();
    },

    toOrderDetail(orderId) {
      if (!orderId) {
        uni.showToast({ title: '工单ID异常，无法查看', icon: 'none' });
        return;
      }
      uni.navigateTo({ url: `/pages/User/workorder/detail?id=${orderId}` });
    },

    toWorkorderList() {
      uni.navigateTo({ url: '/pages/User/workorder/list' });
    },

    // 映射工单类型为文本（兼容type为undefined的情况）
    mapOrderType(type) {
      if (type === undefined) return '未知类型';
      const typeMap = { 1: '维修', 2: '安装', 3: '咨询', 4: '保养' };
      return typeMap[type] || '未知类型';
    },

    formatDate(dateStr) {
      if (!dateStr) return '';
      const date = new Date(dateStr);
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, '0');
      const day = String(date.getDate()).padStart(2, '0');
      const hour = String(date.getHours()).padStart(2, '0');
      const minute = String(date.getMinutes()).padStart(2, '0');
      return `${year}-${month}-${day} ${hour}:${minute}`;
    }
  }
};
</script>

<style scoped>
/* 全局容器：盒模型修正 + 高度占满 */
.my-evaluate-container {
  display: flex;
  flex-direction: column;
  height: 100vh;
  background-color: #f5f7fa;
  box-sizing: border-box; /* 防止padding撑大容器 */
}

/* 顶部导航：固定定位 + 层级 */
.top-nav {
  height: 88rpx;
  background-color: #5555ff;
  display: flex;
  align-items: center;
  padding: 0 32rpx;
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  z-index: 99;
}
.nav-left {
  width: 44rpx;
  height: 44rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}
.back-icon {
  color: #fff;
  font-size: 36rpx;
}
.nav-title {
  flex: 1;
  text-align: center;
  font-size: 36rpx;
  color: #fff;
  font-weight: 500;
}

/* 评价列表容器：避开导航 + 滚动区域 */
.evaluate-list {
  flex: 1;
  padding: 24rpx;
  margin-top: 100rpx; /* 避开顶部导航高度 */
  box-sizing: border-box;
}

/* 加载中状态：居中提示 */
.loading-state {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  height: 300rpx;
  color: #409EFF;
}
.loading-text {
  font-size: 28rpx;
  margin-top: 16rpx;
}

/* 评价项：卡片样式 + 内边距 */
.evaluate-item {
  background-color: #fff;
  border-radius: 12rpx;
  padding: 24rpx;
  margin-bottom: 20rpx;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
  box-sizing: border-box;
}

/* 工单基础信息：修复“工单提交”溢出 */
.order-info {
  margin-bottom: 20rpx;
}
.order-title {
  font-size: 28rpx;
  color: #333;
  font-weight: 500;
  margin-bottom: 8rpx;
  cursor: pointer;
}
.order-title:active {
  color: #409EFF;
}
.order-meta {
  display: flex;
  justify-content: space-between;
  font-size: 22rpx;
  color: #999;
}
/* 工单类型标签：限制宽度 + 省略 */
.order-type {
  max-width: 120rpx;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}
/* 工单提交时间：自适应剩余宽度 */
.order-time {
  flex: 1;
  text-align: right;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

/* 评价核心信息：分隔线 + 内边距 */
.evaluate-core {
  border-top: 1rpx dashed #eee;
  padding-top: 20rpx;
}

/* 评分星星：颜色区分 */
.star-rating {
  margin-bottom: 16rpx;
}
.star {
  font-size: 28rpx;
  color: #ddd;
  margin-right: 4rpx;
}
.star.active {
  color: #FFD700;
}

/* 评价内容：多行省略 */
.evaluate-content {
  font-size: 26rpx;
  color: #666;
  line-height: 1.6;
  margin-bottom: 16rpx;
  word-break: break-all;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
}

/* 关键：强制“查看工单”按钮居右（通过auto margin） */
.evaluate-meta {
  display: flex;
  align-items: center;
  font-size: 22rpx;
  color: #999;
}
.evaluate-time {
  margin-right: auto; /* 把按钮推到最右侧 */
}
.view-order-btn {
  padding: 6rpx 16rpx;
  background-color: #f0f8ff;
  color: #409EFF;
  border-radius: 6rpx;
  font-size: 22rpx;
}

/* 空状态：居中提示 */
.empty-state {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  height: 400rpx;
  color: #999;
}
.empty-icon {
  font-size: 80rpx;
  margin-bottom: 24rpx;
  color: #eee;
}
.empty-text {
  font-size: 28rpx;
  margin-bottom: 32rpx;
  text-align: center;
  padding: 0 40rpx;
}
.to-workorder-btn {
  padding: 12rpx 32rpx;
  background-color: #409EFF;
  color: #fff;
  border-radius: 6rpx;
  font-size: 26rpx;
}

/* 加载更多：居中提示 */
.load-more {
  text-align: center;
  padding: 24rpx 0;
  font-size: 24rpx;
  color: #999;
}
</style>